import datetime
import uuid


from rest_framework.decorators import api_view
from rest_framework.response import Response

from utils.decorator_ import PermissionCheck
from utils.distance import geocode, distance
from .serializer import *

@PermissionCheck('transport.view_logistics')
@api_view(['get'])
def find_logistics(request):
    qs = Logistics.objects.all()
    s = LogisticsSerializer(qs, many=True)
    return Response({'msg': 'ok', 'data': s.data})

@PermissionCheck('transport.view_logdet')
@api_view(['get'])
def find_logdet(request):
    qs = Logdet.objects.all()
    s = LogdetSerializer(qs, many=True)
    return Response({'msg': 'ok', 'data': s.data})

@PermissionCheck('transport.add_logistics')
@api_view(['post'])
def add_logistics(request):
    indent_id = request.data.get('indent')
    transport_id = request.data.get('transport')
    Logistics.objects.create(log_id=uuid.uuid4().hex,
                             indent_id=indent_id,
                             transport_id=transport_id,
                             status='等待配送')
    return Response({'msg': 'OK'})

@PermissionCheck('transport.add_logdet')
@api_view(['post'])
def add_logdet(request):
    log_id = request.data.get('logistics')
    Logdet.objects.create(logdet_id=uuid.uuid4().hex,
                          log_id=log_id,
                          status='等待配送')
    return Response({'msg': 'ok'})

@PermissionCheck('transport.change_logdet')
@api_view(['put'])
def decide_status(request):
    log_id = request.data.get('log_id')
    now_location = request.data.get('now_location')
    logdet = Logdet.objects.get(log_id=log_id)
    log = Logistics.objects.get(log_id=log_id)
    tran_id = log.transport_id
    transport = Transport.objects.get(transport_id=tran_id)
    list1 = geocode(transport.address)
    list2 = geocode(now_location)
    lon1 = list1[0]
    lat1 = list1[1]
    lon2 = list2[0]
    lat2 = list2[1]
    ret = distance(lon1, lat1, lon2, lat2)
    if ret < 1000:
        logdet.status = '已送达'
        log.status = '已送达'
        log.sign_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        logdet.now_location = now_location
        logdet.now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    else:
        logdet.status = '运输中'
        logdet.now_location = now_location
        logdet.now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log.status = '运输中'
    logdet.save()
    log.save()
    return Response({'msg': '更新成功'})

